<!--
 * @Author: Wangtao
 * @Date: 2022-05-17 14:59:01
 * @LastEditors: Wangtao
 * @LastEditTime: 2022-05-30 16:28:20
-->
<template>
  <div class="call-table" style="overflow: hidden">
    <div class="treeDrag">
      <div class="treeHeader">
        <div class="label-checkbox"></div>
        <div class="label-name">{{ $t('config.channel.labelName') }}</div>
        <div class="label-oprate">{{ $t('public.operate') }}</div>
      </div>
      <draggable
        :list="data"
        forceFallback
        handle=".drag"
        style="box-sizing: border-box"
      >
        <div
          class="firstLevel"
          v-for="(item, index) in data"
          :key="item._id"
          v-show="!item.hide"
        >
          <div class="leverFirst list_box">
            <label
              class="el-checkbox label-checkbox"
              :class="checkArr.indexOf(item._id) > -1 ? 'is-checked' : ''"
            >
              <span
                class="el-checkbox__input"
                :class="checkArr.indexOf(item._id) > -1 ? 'is-checked' : ''"
              >
                <span
                  class="el-checkbox__inner"
                  @click.stop="changeCheckbox(item)"
                ></span>
              </span>
            </label>
            <div class="label-name">
              <span v-if="!item.status" class="name-box">{{ item.name }}</span>
              <span
                v-show="item.status"
                :class="{ is_error: item.stopSave == true }"
              >
                <el-input
                  v-model.trim="item.name"
                  class="label-input"
                ></el-input>
                <span
                  @click="handleTreeCancel(index, item)"
                  class="padding-l-10 padding-r-10 cursor operate-btn"
                  >{{ $t('public.cancel') }}</span
                >
                <span
                  @click="handleTreeSave(index, item)"
                  class="padding-r-10 cursor operate-btn"
                  >{{ $t('public.save') }}</span
                >
              </span>
            </div>
            <div class="label-oprate">
              <div v-show="item.name" class="operate-btn">
                <span
                  @click="handleTreeEdit(index, item)"
                  class="padding-r-10 cursor"
                  >{{ $t('public.edit') }}</span
                >
                <span @click="handleDelete(index, item, data)">
                  <span class="cursor is_stopBtn">{{
                    $t('public.delete')
                  }}</span>
                </span>
              </div>
            </div>
          </div>
        </div>
      </draggable>
    </div>
    <div class="label-batch" v-if="checkArr.length > 0">
      <el-checkbox
        v-model.trim="allChecked"
        style="margin-right: 30px"
        @change="checkAll"
        >{{ $t('public.checkAll') }}</el-checkbox
      >
      <span @click="batchDelete(true)"
        ><i class="iconfont icon-piliangqiyong"></i>{{$t('webchat.moreDel')}}</span
      >
      <div class="count">
        {{ $t('public.already') }}<b>{{ checkArr.length || 0 }}</b
        >{{ $t('public.term') }}
        <i class="el-icon-close" @click="restAllChecked"></i>
      </div>
    </div>
  </div>
</template>
<script>
import Vue from 'vue'
import draggable from 'vuedraggable'
import { deepClone } from '@/utils/m7Utils'
export default {
  name: 'treeTable',
  data () {
    return {
      allChecked: false,
      saveFlag: false,
      checkArr: [],
      labelList: [],
      maxLevel: 0,
      stopAddFlag: false,
      addBorderFlag: false,
      data: [],
      cloneData: [],
      dragFlagState: false
    }
  },
  components: { draggable },
  props: ['tableData', 'filterEnable', 'vagueStr'],
  directives: {
    focus: {
      inserted: function (el) {
        el.getElementsByClassName('el-input__inner')[0].focus()
      }
    }
  },
  methods: {
    //      停用
    handleDelete (index, row, parentArr) {
      // deleteKmTags
      this.deleteLabel([row._id]);
    },
    handleAddLabeltest (index, item) {
      if (this.data.length >= 100) {
        this.$message.error(this.$t('knowledge.tip1'))
        return
      }
      this.data.unshift({
        name: '',
        status: true
      })
      this.$emit('emptyStr')
      this.$emit('filterEnableUpdate', 'all')
    },
    handleTreeEdit (index, item) {
      this.$emit('emptyStr')
      this.$set(this.data[index], 'status', true);
    },
    handleTreeCancel (index, item) {
      if (item._id) {
        let cancelName = this.cloneData[index]['name'];
        item.name = cancelName;
        item.status = false;
      } else {
        this.data.splice(index, 1);
      }
    },
    handleTreeSave (index, item) {
      if (!item.name) {
        this.$message.error(this.$t('knowledge.tip2'));
        return;
      }
      if (item.name.length > 30) {
        this.$message.error(this.$t('knowledge.tip3'));
        return;
      }
      if (item._id) {
        this.updateLabel(item, index);
      } else {
        this.saveLabel(item, index);
      }
    },
    updateLabel (item, index) {
      let query = {
        _id: item._id,
        name: item.name
      }
      this.$store.dispatch('updateKmTag', query).then((resp) => {
        if (resp.success) {
          this.updateData(index, query);
          this.$message.success(this.$t('knowledge.tip4'));
        }
      })
    },
    saveLabel (item, index) {
      let query = {
        name: item.name
      }
      this.$store.dispatch('addKmTag', query).then((resp) => {
        if (resp.success) {
          query._id = resp.data._id;
          this.updateData(index, query);
          this.$message.success(this.$t('knowledge.tip5'));
        }
      })
    },
    deleteLabel (ids) {
      this.$confirm(this.$t('knowledge.tip6'), this.$t('knowledge.tip7'), {
        confirmButtonText: this.$t('public.confirm'),
        cancelButtonText: this.$t('public.cancel'),
        cancelButtonClass: 'primary_btn',
        confirmButtonClass: 'primary_btn',
        type: 'warning'
      }).then(() => {
        let query = { idList: ids }
        this.$store.dispatch('deleteKmTags', query).then((resp) => {
          if (resp.success) {
            this.deleteData(query.idList);
            this.$message.success(this.$t('knowledge.tip8'));
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: this.$t('public.cancel')
        })
      })
    },
    changeCheckbox (item) { // 递归处理，父级选中或取消选中的时候，子级也跟着操作
      const itemIndex = this.checkArr.indexOf(`${item._id}`);
      if (this.checkArr.indexOf(`${item._id}`) === -1) { // 父级有选中，子级全部选中
        this.checkArr.push(`${item._id}`)
      } else {
        if (itemIndex > -1) {
          this.checkArr.splice(itemIndex, 1)
        }
      }
    },
    checkAll (checked) {
      if (checked) {
        this.checkArr = [] // 全选的时候，先把之前选中的置空，重新选择
        this.data.forEach(item => {
          this.changeCheckbox(item);
        })
      } else {
        this.restAllChecked()
      }
    },
    restAllChecked () { // 把所有选中的重置成未选中
      this.allChecked = false
      this.checkArr = []
    },
    batchEnableOrDisabled (enabled) {
      this.$store.dispatch('batchUpdateCallLabelStatus', { ids: this.checkArr, enabled }).then((resp) => {
        if (resp && resp.success) {
          this.restAllChecked()
          this.$emit('refreshData')
        }
      })
    },
    batchDelete () {
      this.deleteLabel(this.checkArr);
    },
    forceUpdate (text) {
      // this.$forceUpdate()
      let list = this.data.map((item) => {
        let setObj = item;
        setObj.hide = false;
        if (text) {
          if (item.name.indexOf(text) === -1) {
            setObj.hide = true;
          }
        }
        return setObj;
      });
      this.$set(this, 'data', list);
    },
    updateData (index, item) {
      this.$set(this.data, index, deepClone(item));
      this.cloneData[index] = deepClone(item);
    },
    deleteData (ids) {
      let list = this.data.filter((item) => {
        return ids.indexOf(item._id) === -1;
      })
      this.$set(this, 'data', deepClone(list));
      this.cloneData = deepClone(list);
    }
  },
  beforeMount () {
    this.cloneData = deepClone(this.tableData);
    this.data = this.tableData;
  },
  watch: {
    filterEnable (value, oldVal) {
      this.restAllChecked()
      this.forceUpdate()
    }
  }
}
</script>
<style lang="stylus" scoped>
@import '../../../../../assets/common.styl'
.label-name
  width calc(80% - 50px)
.label-oprate
  width 20%
.name-box
  overflow hidden
  text-overflow ellipsis
  white-space nowrap
.treeHeader
  border 1px solid #e7e7eb
  border-bottom 0px
  border-right 0px
  display flex
  background #f4f5f9
  box-sizing border-box
  font-weight bold
.treeHeader > div
  box-sizing border-box
  border-right 1px solid #e7e7eb
  padding 10px
.operate
  padding 0 5px 0
.drag
  cursor pointer
.treeChild
  /* display none */
.list_box
  > div
    border-right 1px solid #e7e7eb
    padding 10px
    box-sizing border-box
    display flex
    align-items center
  display flex
  flex-direction row
  width 100%
  border-bottom 1px solid #e7e7eb
  border-left 1px solid #e7e7eb
.label-checkbox
  width 50px !important
  border-right 1px solid #e7e7eb
  >>>.el-checkbox__input
    margin 13px 0 0 17px
.firstLevel:nth-of-type(1)
  border-top 1px solid #e7e7eb
.call-table
  /* margin 10px 20px */
  .lab-name
    margin-left 10px
    max-width 20em
    text-overflow ellipsis
    overflow hidden
    white-space nowrap
  .paddelvel2
    padding-left 21px
  .paddelvel3
    padding-left 36px
  .paddelvel4
    padding-left 51px
  .paddelvel5
    padding-left 66px
  .is_stop
    color #ff9100
  .padding-r-10
    padding-right 10px
  .padding-l-10
    padding-left 10px
  .operate-btn
    color $c-main
  .is_stopBtn
    color $c-pink
  .cursor
    cursor pointer
  .icon-zhankai
    cursor pointer
  .icon-zuixiaohua
    cursor pointer
  .label-input
    width 170px
    display inline-block
    padding-left 5px
  .delete
    color $c-pink
    padding-left 10px
    vertical-align middle
.label-batch
  box-sizing border-box
  display flex
  align-items center
  width calc(100vw - 56px)
  height 40px
  padding-left 10px
  background #fff
  position fixed
  z-index 1990
  right 0
  bottom 0
  box-shadow 1px -2px 7px rgba(0, 0, 0, 0.1)
  font-size 12px
  color #595959
  > span
    margin-right 30px
    &:hover
      cursor pointer
      color $cf-gray0
      .iconfont
        color $c-main
    .iconfont
      margin-right 5px
      font-size 14px
.call-channel-config .label-batch
  width calc(100vw - 237px)
.navMenuState .label-batch
  width calc(100vw - 313px)
.navMenuState .call-channel-config .label-batch
  width calc(100vw - 295px)
.count
  position absolute
  right 18px
  b
    color $c-main
  .el-icon-close
    color $c-pink
    font-size 14px
    font-weight 700
    cursor pointer
</style>




















